package cn.jinjimi.app.presenter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.app.controller.CustomerController;
import cn.jinjimi.domain.data.dto.HolidayCardsDto;
import cn.jinjimi.app.entity.CardItemData;
import cn.jinjimi.app.entity.CardListBean;
import cn.jinjimi.app.entity.SceneCardRespData;
import cn.jinjimi.app.entity.SceneItem;
import cn.jinjimi.app.entity.SceneRespData;
import cn.jinjimi.app.interfaces.CardFragmentView;
import cn.jinjimi.app.store.DatabaseManager;
import cn.jinjimi.app.main.fragment.CardFragment;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import bolts.Continuation;
import bolts.Task;

/**
 * Created by lforxeverc on 2016/10/19.
 */

public class CardPresenter {
    public static final int DefaultPage = 1;
    public static final int HolidayLimit = 4;
    public static final int SceneLimit = 12;
    public static final int CardLimit = 12;
    CardFragmentView mView;
    CardFragment.LoadType mLoadType;
    int currentPage = DefaultPage;
    int mCardTypeId = 0;


    public CardPresenter(CardFragmentView view, CardFragment.LoadType type) {
        mView = view;
        mLoadType = type;
    }

    public void loadMoreData() {
        executeTask(false);
    }

    public void refresh() {
        executeTask(true);
    }


    public void saveCache(List<CardItemData> data) {
        if (data != null && !data.isEmpty())
            DatabaseManager.getInstance().getCacheDao().saveCacheData(data, getCacheKeyWithType(), false);
    }

    public void loadCache() {
        String cache = DatabaseManager.getInstance().getCacheDao().getCacheData(getCacheKeyWithType(), false);
        if (!StringUtils.isEmpty(cache)) {
            Gson gson = new Gson();
            Type type = new TypeToken<List<CardItemData>>() {
            }.getType();
            List<CardItemData> data = gson.fromJson(cache, type);
            mView.onLoadCache(data);
        } else {
            mView.onLoadCache(null);
        }

    }

    private void executeTask(final boolean refresh) {
        if (mLoadType == CardFragment.LoadType.HOLIDAY) {
            if (refresh)
                currentPage = DefaultPage;
            CustomerController.getHolidayCards(currentPage, HolidayLimit).continueWith(new Continuation<HolidayCardsDto, Object>() {
                @Override
                public Object then(Task<HolidayCardsDto> task) throws Exception {

                    HolidayCardsDto rawData = task.getResult();
                    if (rawData != null && rawData.isOk) {
                        boolean nomore = rawData.data == null || rawData.data.size() < HolidayLimit;
                        mView.onLoadSuccess(currentPage, parseHolidayDtoData(rawData), nomore);
                        currentPage++;
                    } else {
                        mView.onLoadFail(currentPage, "加载失败，请稍后再试");
                    }
                    return null;
                }
            }, Task.UI_THREAD_EXECUTOR);
        } else if (mLoadType == CardFragment.LoadType.SCENE_LIST) {
            CustomerController.getSceneList().continueWith(new Continuation<SceneRespData, Object>() {
                @Override
                public Object then(Task<SceneRespData> task) throws Exception {
                    SceneRespData data = task.getResult();
                    if (data != null && data.isOk) {
                        mView.onLoadSuccess(DefaultPage, parseSceneData(data), true);
                    } else {
                        mView.onLoadFail(DefaultPage, "加载失败，请稍后再试");
                    }
                    return null;
                }
            }, Task.UI_THREAD_EXECUTOR);
        } else if (mLoadType == CardFragment.LoadType.HOLIDAY_WITH_ID || mLoadType == CardFragment.LoadType.BIRTHDAY) {
            if (refresh)
                currentPage = DefaultPage;
            CustomerController.getCardList(mCardTypeId, currentPage, CardLimit).continueWith(new Continuation<CardListBean, Object>() {
                @Override
                public Object then(Task<CardListBean> task) throws Exception {
                    CardListBean result = task.getResult();
                    if (result != null && result.isOk) {
                        List<CardItemData> data = parseCarBeanData(result.getGreetingCards(), mCardTypeId);
                        mView.onLoadSuccess(currentPage, data, data.size() < CardLimit);
                        currentPage++;
                    } else {
                        mView.onLoadFail(currentPage, "加载失败，请稍后再试");
                    }
                    return null;
                }
            }, Task.UI_THREAD_EXECUTOR);
        } else if (mLoadType == CardFragment.LoadType.SCENE_WITH_ID) {
            if (refresh)
                currentPage = DefaultPage;
            CustomerController.getSceneCardList(mCardTypeId, currentPage, SceneLimit).continueWith(new Continuation<SceneCardRespData, Object>() {
                @Override
                public Object then(Task<SceneCardRespData> task) throws Exception {
                    SceneCardRespData result = task.getResult();
                    if (result != null && result.isOk) {
                        boolean noMore = result.data == null || result.data.size() < SceneLimit;
                        mView.onLoadSuccess(currentPage, parseSceneCards(result), noMore);
                        currentPage++;
                    } else {
                        mView.onLoadFail(currentPage, "加载失败，请稍后再试");
                    }
                    return null;
                }
            }, Task.UI_THREAD_EXECUTOR);
        }
    }

    private List<CardItemData> parseCarBeanData(List<CardListBean.CardBean> raw, int holidayId) {
        List<CardItemData> result = new ArrayList<>();
        if (raw == null || raw.isEmpty()) return result;
        for (CardListBean.CardBean temp : raw) {

            CardItemData item = new CardItemData();
            item.type = CardItemData.Type.ITEM;
            item.itemData = temp;
            item.itemData.setHolidayId(holidayId);
            result.add(item);

        }
        return result;
    }

    private List<CardItemData> parseHolidayDtoData(HolidayCardsDto dto) {
        List<CardItemData> result = new ArrayList<>();
        List<CardListBean> rawData = dto.data;
        if (rawData != null && !rawData.isEmpty()) {
            for (CardListBean temp : rawData) {
                //增加节日头部信息
                CardItemData header = new CardItemData();
                header.type = CardItemData.Type.HEADER;
                header.headerData.name = temp.getHolidayName();
                header.headerData.startTs = temp.getStartTime();
                header.headerData.endTs = temp.getEndTime();
                header.headerData.restDays = temp.getRestDays();
                result.add(header);
                //节日贺卡格式化
                List<CardListBean.CardBean> cardBeans = temp.getGreetingCards();
                int holidayId = temp.getHolidayId();
                List<CardItemData> items = parseCarBeanData(cardBeans, holidayId);
                result.addAll(items);

            }
        }
        return result;
    }

    private List<CardItemData> parseSceneData(SceneRespData data) {
        List<CardItemData> result = new ArrayList<>();
        if (data != null && data.data != null && !data.data.isEmpty()) {
            for (SceneItem temp : data.data) {
                CardItemData item = new CardItemData();
                item.type = CardItemData.Type.SCENE;
                item.sceneData = temp;
                result.add(item);
            }
        }
        return result;
    }

    private List<CardItemData> parseSceneCards(SceneCardRespData data) {
        List<CardItemData> result = new ArrayList<>();
        if (data != null && data.data != null && !data.data.isEmpty()) {
            for (CardListBean.CardBean temp : data.data) {
                CardItemData item = new CardItemData();
                item.type = CardItemData.Type.ITEM;
                item.itemData = temp;
                result.add(item);
            }
        }
        return result;
    }

    public void setCardTypeId(int mCardTypeId) {
        this.mCardTypeId = mCardTypeId;
    }

    private String getCacheKeyWithType() {
        String key = "";
        if (mLoadType == CardFragment.LoadType.BIRTHDAY) {
            key = "birthday_card_cache";
        } else if (mLoadType == CardFragment.LoadType.HOLIDAY) {
            key = "holiday_card_cache";
        } else if (mLoadType == CardFragment.LoadType.SCENE_LIST) {
            key = "scene_card_cache";
        } else if (mLoadType == CardFragment.LoadType.HOLIDAY_WITH_ID) {
            key = "holiday_card_id_" + mCardTypeId + "_cache";
        } else if (mLoadType == CardFragment.LoadType.SCENE_WITH_ID) {
            key = "scene_card_id_" + mCardTypeId + "_cache";
        }
        return key;
    }


}
